<?php
namespace control;

/*
*运费明细类
*/


class freightDetailsClass extends adIndexClass
{
    private const title = '运费明细';
    private const page = 'freightDetails';
    private const table = 'sale_send_order_car';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'externalSearch':
                $tr = [
                    'send_date'          => [
                        'name'  => '发货日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "运单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sendOrderNo'  => [
                        'name'  => "发货单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 150,
                    ],
                    'unit_name'  => [
                        'name'  => "单位名称",
                        'width' => 150,
                    ],
                    'car_no'  => [
                        'name'  => "车牌号",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'driver'         => [
                        'name'  => '驾驶员',
                        'width' => 100,
                    ],
                    'contactTel'          => [
                        'name'  => '联系电话',
                        'width' => 100,
                    ],
                    'idCard'          => [
                        'name'  => '身份证号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'actual_weight'          => [
                        'name'  => '实际装货吨数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'freight'          => [
                        'name'  => '运费（'.static::$unit.'）',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'receipt_date'          => [
                        'name'  => '签收日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'pay_freight'          => [
                        'name'  => '运费收款',
                        'width' => 100,
                    ]
                ];
                break;
            case 'listSearch':
                $tr = [

                    'orderNo' => [
                        'name'  => "运单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'time'  => [
                        'name'  => "日期",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyOrderNo'  => [
                        'name'  => "客户编码",
                        'width' => 150,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 150,
                    ],
                    'freight'          => [
                        'name'  => '本次运费',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'changeFreight'          => [
                        'name'  => '调整运费',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
                break;
            default:
                $tr = [
                    'send_date'          => [
                        'name'  => '发货日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "运单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sendOrderNo'  => [
                        'name'  => "发货单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 150,
                    ],
                    'car_no'  => [
                        'name'  => "车牌号",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'driver'         => [
                        'name'  => '驾驶员',
                        'width' => 100,
                    ],
                    'contactTel'          => [
                        'name'  => '联系电话',
                        'width' => 100,
                    ],
                    'idCard'          => [
                        'name'  => '身份证号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'actual_weight'          => [
                        'name'  => '实际装货吨数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'freight'          => [
                        'name'  => '运费（'.static::$unit.'）',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'receipt_date'          => [
                        'name'  => '签收日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'pay_freight'          => [
                        'name'  => '运费收款',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "发货日期" => text(array("name" => "send_date", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "运单号"   => text(array("name" => "orderNo")),
                    "客户"   => text(array("name" => "companyName")),
                ],
                [
                    "发货单号"   => text(array("name" => "sendOrderNo")),
                    "车牌号"   => text(array("name" => "car_no")),
                    "驾驶员"   => text(array("name" => "driver")),
                ],
                [
                    "联系电话"   => text(array("name" => "contactTel")),
                    "身份证号"   => text(array("name" => "idCard")),
                    '运费收款' => select(["name" => "pay_freight", 'option' => ['1'=>'是', '0'=>'否']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*运费明细-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'payment','type':'inside'})\">运费收款</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "car.orderNo" => $this->post('orderNo'),
            "car.car_no" => $this->post('car_no'),
            "car.driver" => $this->post('driver'),
            "car.contactTel" => $this->post('contactTel'),
            "car.idCard" => $this->post('idCard'),
            "send.orderNo" => $this->post('sendOrderNo'),
        );
        //全等查询数组
        $equal = array(
            'car.coid' => self::$coid,
            'car.pay_freight' => $this->post('pay_freight'),
            'car.type' => 0,
        );

        $and = " and send.send_state > 1 ";
        if ($this->post('send_date')) {
            $and .= self::timeComparison($this->post('send_date'),field: 'send.send_date');
        }
        if($this->post('unit_name')){
            $and .= " and car.car_id in (select id from logistics_transfer_car where unit_name like '%".$this->post('unit_name')."%') ";
        }
        if($this->post('companyName')){
            $and .= " and send.khid in (select khid from kehu where companyName like '%".$this->post('companyName')."%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'car.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as car left join delivery_order as send on car.orderId = send.id ",
            "where" => $where,
            "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu = query("kehu"," khid = '".$array['khid']."' ",'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'freight':
                        $row[] = self::lostZero($array['freight']);
                        break;
                    case 'pay_freight':
                        $row[] = $array['pay_freight']>0?'是':'否';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table." as car left join delivery_order as send on car.orderId = send.id ",
            'single' => $where,
            'field'  => "ifnull(sum(car.actual_weight),0) as actual_weight,ifnull(sum(car.freight),0) as freight",
        ]);
        $total    = [
            'actual_weight'        => self::lostZero($totalQuery['actual_weight'], 'numPrecision'),
            'freight'   => self::lostZero($totalQuery['freight'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
                    "table" => self::table." as car left join delivery_order as send on car.orderId = send.id ",
                    "where" => "car.id in ('".implode("','", $checkedId)."') order by car.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '发货日期'=>$array['send_date'],
                            '运单号'=>$array['orderNo'],
                            '发货单号'=>$array['sendOrderNo'],
                            '车牌号'=>$array['car_no'],
                            '驾驶员'=>$array['driver'],
                            '联系电话'=>$array['contactTel'],
                            '身份证号'=>$array['idCard'],
                            '实际装货吨数'=>$array['actual_weight'],
                            '运费'=> self::lostZero($array['freight']),
                            '签收日期'=>$array['receipt_date'],
                            '运费收款'=>$array['pay_freight']>0?'是':'否',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了内部车辆运费明细";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "内部车辆运费明细.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /*列表页-查询条件*/
    public function externalOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "发货日期" => text(array("name" => "send_date", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "运单号"   => text(array("name" => "orderNo")),
                    "客户"   => text(array("name" => "companyName")),
                ],
                [
                    "发货单号"   => text(array("name" => "sendOrderNo")),
                    "单位名称"   => text(array("name" => "unit_name")),
                    "车牌号"   => text(array("name" => "car_no")),
                ],
                [
                    "驾驶员"   => text(array("name" => "driver")),
                    "联系电话"   => text(array("name" => "contactTel")),
                    '运费收款' => select(["name" => "pay_freight", 'option' => ['1'=>'是', '0'=>'否']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 外调车辆
     *
     */
    public function external(): bool|string
    {
        $html = $this->externalOptions(false);
        //控件
        $button = "";
        if ($this->power('freightDetailsExternal', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportExternalData',classify:'外调车辆运费明细'})\">导出</span>";
        }
        if ($this->power('freightDetailsExternal', "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'payment','type':'outside'})\">运费收款</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 外调车辆
     * @return bool|string
     */
    public function externalSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "car.orderNo" => $this->post('orderNo'),
            "car.car_no" => $this->post('car_no'),
            "car.driver" => $this->post('driver'),
            "car.contactTel" => $this->post('contactTel'),
            "car.idCard" => $this->post('idCard'),
            "send.orderNo" => $this->post('sendOrderNo'),
        );
        //全等查询数组
        $equal = array(
            'car.coid' => self::$coid,
            'car.pay_freight' => $this->post('pay_freight'),
            'car.type' => 1,
        );

        $and = " and send.send_state > 1 ";
        if ($this->post('send_date')) {
            $and .= self::timeComparison($this->post('send_date'),field: 'send.send_date');
        }
        if($this->post('unit_name')){
            $and .= " and car.car_id in (select id from logistics_transfer_car where unit_name like '%".$this->post('unit_name')."%') ";
        }
        if($this->post('companyName')){
            $and .= " and send.khid in (select khid from kehu where companyName like '%".$this->post('companyName')."%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'car.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as car left join delivery_order as send on car.orderId = send.id ",
            "where" => $where,
            "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
            "order" => $orderBy['orderBy']
        ));
        $_SESSION['external']['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("externalForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu = query("kehu"," khid = '".$array['khid']."' ",'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'unit_name':
                        $logistics_transfer_car = query("logistics_transfer_car"," id = '$array[car_id]' ");
                        $row[] = $logistics_transfer_car['unit_name'];
                        break;
                    case 'freight':
                        $row[] = self::lostZero($array['freight']);
                        break;
                    case 'pay_freight':
                        $row[] = $array['pay_freight']>0?'是':'否';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table." as car left join delivery_order as send on car.orderId = send.id ",
            'single' => $where,
            'field'  => "ifnull(sum(car.actual_weight),0) as actual_weight,ifnull(sum(car.freight),0) as freight",
        ]);
        $total    = [
            'actual_weight'        => self::lostZero($totalQuery['actual_weight'], 'numPrecision'),
            'freight'   => self::lostZero($totalQuery['freight'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='externalForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportExternalData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('freightDetailsExternal', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
                    "table" => self::table." as car left join delivery_order as send on car.orderId = send.id ",
                    "where" => "car.id in ('".implode("','", $checkedId)."') order by car.time desc",
                ))['array'];
            }else{
                $sql = $_SESSION['external']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $logistics_transfer_car = query("logistics_transfer_car"," id = '$array[car_id]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '发货日期'=>$array['send_date'],
                            '运单号'=>$array['orderNo'],
                            '发货单号'=>$array['sendOrderNo'],
                            '单位名称'=> $logistics_transfer_car['unit_name'],
                            '车牌号'=>$array['car_no'],
                            '驾驶员'=>$array['driver'],
                            '联系电话'=>$array['contactTel'],
                            '身份证号'=>$array['idCard'],
                            '实际装货吨数'=>$array['actual_weight'],
                            '运费'=>self::lostZero($array['freight']),
                            '签收日期'=>$array['receipt_date'],
                            '运费收款'=>$array['pay_freight']>0?'是':'否',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了外调车辆运费明细";
            $this->logText(["type" => 'freightDetailsExternal', "text" => $text]);
            $this->excelOut($title, $data, "外调车辆运费明细.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = $hidden = '';
        switch ($act) {
            case 'payment':
                $act = 'edit';
                $msg = '运费收款';
                $title = '是否确认操作选中的运费付款？';
                $function = 'payment';
                $form = $this->post('type')=='inside'?self::page . 'OperateForm, listForm':self::page . 'OperateForm, externalForm';
                $power = '';
                $word = true;
                $hidden = hidden(['name'=>'type','value'=>$this->post('type')]);
                break;
        }
        if (!$this->power($this->post('type')=='inside'?self::page:'freightDetailsExternal', $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
                'hidden' => $hidden
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 运费收款
     * @return bool|string
     */
    public function payment()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit") && !$this->power('freightDetailsExternal', "edit")) {
            $json['warn'] = "你没有操作运费付款的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['pay_freight'] == 1) {
                    $warn = "付款失败：已付款，请勿重复操作";
                } else {
                    update(array('table' => self::table, 'field' => ['pay_freight' => 1,'pay_time'=>$this->time], 'where' => "id = '$id'"));
                    //返回
                    $warn = "操作成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "操作了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "操作了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '外调车辆运费明细'=>[
                [
                    'columnName'=>'发货日期',
                    'aliasName'=>'发货日期',
                ],
                [
                    'columnName'=>'运单号',
                    'aliasName'=>'运单号',
                ],
                [
                    'columnName'=>'发货单号',
                    'aliasName'=>'发货单号',
                ],
                [
                    'columnName'=>'单位名称',
                    'aliasName'=>'单位名称',
                ],
                [
                    'columnName'=>'车牌号',
                    'aliasName'=>'车牌号',
                ],
                [
                    'columnName'=>'驾驶员',
                    'aliasName'=>'驾驶员',
                ],
                [
                    'columnName'=>'联系电话',
                    'aliasName'=>'联系电话',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'实际装货吨数',
                    'aliasName'=>'实际装货吨数',
                ],
                [
                    'columnName'=>'运费',
                    'aliasName'=>'运费（元）',
                ],
                [
                    'columnName'=>'签收日期',
                    'aliasName'=>'签收日期',
                ],
                [
                    'columnName'=>'运费收款',
                    'aliasName'=>'运费收款',
                ],
            ],
            '运费明细'=>[
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'本次运费',
                    'aliasName'=>'本次运费',
                ],
                [
                    'columnName'=>'调整运费',
                    'aliasName'=>'调整运费',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'发货日期',
                    'aliasName'=>'发货日期',
                ],
                [
                    'columnName'=>'运单号',
                    'aliasName'=>'运单号',
                ],
                [
                    'columnName'=>'发货单号',
                    'aliasName'=>'发货单号',
                ],
                [
                    'columnName'=>'车牌号',
                    'aliasName'=>'车牌号',
                ],
                [
                    'columnName'=>'驾驶员',
                    'aliasName'=>'驾驶员',
                ],
                [
                    'columnName'=>'联系电话',
                    'aliasName'=>'联系电话',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'实际装货吨数',
                    'aliasName'=>'实际装货吨数',
                ],
                [
                    'columnName'=>'运费',
                    'aliasName'=>'运费（元）',
                ],
                [
                    'columnName'=>'签收日期',
                    'aliasName'=>'签收日期',
                ],
                [
                    'columnName'=>'运费收款',
                    'aliasName'=>'运费收款',
                ],
            ]
        };
    }

    /*列表页-查询条件*/
    public function listOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码"   => text(array("name" => "orderNo")),
                    "客户"   => text(array("name" => "name")),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 运费明细
     *
     */
    public function list(): bool|string
    {
        $html = $this->listOptions(false);
        //控件
        $button = "";
        if ($this->power('freightDetailsList', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportListData',classify:'运费明细'})\">导出</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 运费明细
     * @return bool|string
     */
    public function listSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "kehu.orderNo" => $this->post('orderNo'),
            "kehu.car_no" => $this->post('car_no'),
        );
        //全等查询数组
        $equal = array(
            'car.coid' => self::$coid,
        );

        $and = " and send.send_state > 1 ";

        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'car.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as car left join delivery_order as send on car.orderId = send.id left join kehu on send.khid = kehu.khid",
            "where" => $where,
            "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
            "order" => $orderBy['orderBy']
        ));
        $_SESSION['list']['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                $kehu = query("kehu"," khid = '".$array['khid']."' ");
                $freight_change = query("freight_change"," freightId = '".$array['id']."' ");
                switch ($key) {
                    case 'companyName':
                        $row[] = $kehu['companyName'];
                        break;
                    case 'companyOrderNo':
                        $row[] = $kehu['orderNo'];
                        break;
                    case 'freight':
                        $row[] = self::lostZero($freight_change['freight']);
                        break;
                    case 'changeFreight':
                        $row[] = self::lostZero($freight_change['newFreight'] ?? 0);
                        break;
                    case 'state':
                        $row[] = $freight_change['newFreight']?'未调整':'已调整';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }

        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportListData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('freightDetailsList', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "field" => " send.orderNo as sendOrderNo,send.send_date,send.send_state,send.receipt_date,send.khid,car.* ",
                    "table" => self::table." as car left join delivery_order as send on car.orderId = send.id ",
                    "where" => "car.id in ('".implode("','", $checkedId)."') order by car.time desc",
                ))['array'];
            }else{
                $sql = $_SESSION['list']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $logistics_transfer_car = query("logistics_transfer_car"," id = '$array[car_id]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '发货日期'=>$array['send_date'],
                            '运单号'=>$array['orderNo'],
                            '发货单号'=>$array['sendOrderNo'],
                            '单位名称'=> $logistics_transfer_car['unit_name'],
                            '车牌号'=>$array['car_no'],
                            '驾驶员'=>$array['driver'],
                            '联系电话'=>$array['contactTel'],
                            '身份证号'=>$array['idCard'],
                            '实际装货吨数'=>$array['actual_weight'],
                            '运费'=>self::lostZero($array['freight']),
                            '签收日期'=>$array['receipt_date'],
                            '运费收款'=>$array['pay_freight']>0?'是':'否',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了外调车辆运费明细";
            $this->logText(["type" => 'freightDetailsList', "text" => $text]);
            $this->excelOut($title, $data, "运费明细.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

}
